package com.eric.utils.http;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;

import java.util.Map;

/**
 * @description:
 * @author: liuBing
 * @create: 2023-12-06 10:53
 **/
@Slf4j
public class HTHttpUtilNew {

    @AllArgsConstructor
    @Getter
    public enum HttpEnum {
        SIMPLE("");

        private final String desc;
    }

    private static final Integer DEFAULT_TIME_OUT = 100000;

    private static String doHttp(HttpEnum httpEnum,
                                 HttpMethod method,
                                 String url,
                                 Map<String, String> header,
                                 Map<String, Object> form,
                                 Object body,
                                 int timeOut) {
        String bodyStr = JSONUtil.toJsonStr(body);
        // 设置请求超时时间
        int finalTimeOut = timeOut > 0 ? timeOut : DEFAULT_TIME_OUT;

        // 打印日志
        String desc = httpEnum.getDesc();
        log.info("[{}]请求路径: {}", desc, url);
        log.info("[{}]请求协议: {}", desc, method);
        if (MapUtil.isNotEmpty(header)) {
            log.info("[{}]请求头: {}", desc, JSONUtil.toJsonStr(header));
        }
        if (MapUtil.isNotEmpty(form)) {
            log.info("[{}]请求表单: {}", desc, JSONUtil.toJsonStr(form));
        }
        if (StrUtil.isNotBlank(bodyStr)) {
            log.info("[{}]请求体: {}", desc, bodyStr);
        }

        // 发送请求
        String result ;
        TimeInterval timer = DateUtil.timer();
        if (method.equals(HttpMethod.POST)) {
            HttpRequest httpRequest = HttpUtil.createPost(url).addHeaders(header).timeout(finalTimeOut);
            result = MapUtil.isNotEmpty(form)
                    ? httpRequest.form(form).execute().body()
                    : httpRequest.body(bodyStr).execute().body();
        } else if (method.equals(HttpMethod.GET)) {
            result = HttpUtil.createGet(url).addHeaders(header).timeout(finalTimeOut).form(form).execute().body();
        } else {
            throw new RuntimeException("请求方式错误");
        }

        log.info("[{}]请求结果: {}", desc, result);
        log.info("[{}]请求耗时: {}", desc, timer.interval() + "毫秒");
        return result;
    }
}
